﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceConcurrentEventAndFee")]
	public class ConferenceConcurrentEventAndFeeController : BaseDbController
	{
		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConcurrentEventAndFee;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceConcurrentEventAndFeeModel();
			model.ConferenceId = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ConferenceConcurrentEventAndFeeModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.ConcurrentEventMaster.AsNoTracking().Where(x => !string.IsNullOrEmpty(x.Status) && x.ConferenceId == model.ConferenceId);

			if (!string.IsNullOrWhiteSpace(model.EventName))
			{
				sql = sql.Where(x => x.EventName.Contains(model.EventName));
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.EventName).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				EventName = x.EventName,
				EventTime = x.EventTime,
				EventPlace = x.EventPlace,
				Link = x.Link,
				Contact = x.Contact,
				ContactPhone = x.ContactPhone,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				IsAllIdentity = x.IsAllIdentity,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						x.CreateDate.Value.ToString("yyyy-MM-dd") :
						x.CreateDate.Value.ToString("MM/dd/yyyy"),
				CreateIP = x.CreateIP,
				Creator = x.Creator
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var data = await DbContext.ConcurrentEventMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (data != null)
			{
				var result = new
				{
					eventName = data.EventName,
					eventTime = data.EventTime,
					eventPlace = data.EventPlace,
					link = data.Link,
					contact = data.Contact,
					contactPhone = data.ContactPhone,
					sort = data.Sort,
					status = data.Status,
					remark = data.Remark,
					isAllIdentity = data.IsAllIdentity.ToString().ToLower(),
				};
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Create/{ConferenceId}")]
		public async Task<JsonResult> Create(ConferenceConcurrentEventAndFeeModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.ConcurrentEventMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConferenceId == model.ConferenceId &&
						x.EventName == model.EventName);

			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.EventName)),
						JsonRequestBehavior.AllowGet);
			}

			var ConcurrentEventMaster = new ConcurrentEventMaster
			{
				ID = Utility.GetTableId(ConstValues.TableName.ConcurrentEventMaster),
				EventName = model.EventName?.Trim(),
				EventTime = model.EventTime?.Trim(),
				EventPlace = model.EventPlace?.Trim(),
				Link = model.Link?.Trim(),
				Contact = model.Contact?.Trim(),
				ContactPhone = model.ContactPhone?.Trim(),
				ConferenceId = model.ConferenceId,
				Status = model.Status,
				Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
				Remark = model.Remark?.Trim(),
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = DateTime.Now,
				IsAllIdentity = model.ChargeType == ConstValues.GenericSelectionType.有 ? true : false,
			};

			DbContext.ConcurrentEventMaster.Add(ConcurrentEventMaster);
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Modify/{ConferenceId}")]
		public async Task<JsonResult> Modify(ConferenceConcurrentEventAndFeeModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var isSelected = false;
			var feeConcurrentEventMaster = DbContext.FeeConcurrentEventMaster.AsNoTracking().Where(x => x.ConcurrentEventId == model.Id).ToList();     
			foreach( var feeEvent in feeConcurrentEventMaster)
			{
				var profilePaymentInfo = DbContext.ProfilePaymentInfo.AsNoTracking().FirstOrDefault(x => x.FeeId == feeEvent.ID);
				if(profilePaymentInfo != null)
				{
					isSelected = true;
					break;
					//return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgUsingCanNotChange),JsonRequestBehavior.AllowGet);
				}
			}

			var exist = await DbContext.ConcurrentEventMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID != model.Id &&
						x.ConferenceId == model.ConferenceId &&
						x.EventName == model.EventName);

			if (exist != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.EventName)),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.ConcurrentEventMaster
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				
				if (result.IsAllIdentity != (model.ChargeType == ConstValues.GenericSelectionType.有 ? true : false) && feeConcurrentEventMaster.Count > 0)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgChangeIsAllIdentity),
						JsonRequestBehavior.AllowGet);
				}

				if (isSelected)
				{
					result.EventName = model.EventName?.Trim();
					result.EventTime = model.EventTime?.Trim();
					result.EventPlace = model.EventPlace?.Trim();
					result.Link = model.Link?.Trim();
					result.Contact = model.Contact?.Trim();
					result.ContactPhone = model.ContactPhone?.Trim();
					result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
					result.Remark = model.Remark?.Trim();
					//result.Status = model.Status;
					//result.IsAllIdentity = model.ChargeType == ConstValues.GenericSelectionType.有 ? true : false;

					result.Updater = LoginUser.UserName;
					result.UpdateDate = DateTime.Now;
					result.UpdateIP = LoginUser.IP;
				}
				else
				{
					result.EventName = model.EventName?.Trim();
					result.EventTime = model.EventTime?.Trim();
					result.EventPlace = model.EventPlace?.Trim();
					result.Link = model.Link?.Trim();
					result.Contact = model.Contact?.Trim();
					result.ContactPhone = model.ContactPhone?.Trim();
					result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
					result.Remark = model.Remark?.Trim();
					result.Status = model.Status;
					result.IsAllIdentity = model.ChargeType == ConstValues.GenericSelectionType.有 ? true : false;

					result.Updater = LoginUser.UserName;
					result.UpdateDate = DateTime.Now;
					result.UpdateIP = LoginUser.IP;
				}
				
				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Delete/{ConferenceId}")]
		public async Task<JsonResult> Delete(ConferenceConcurrentEventAndFeeModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var feeConcurrentEventMaster = DbContext.FeeConcurrentEventMaster.AsNoTracking().Where(x => x.ConcurrentEventId == model.Id).ToList();
			foreach (var feeEvent in feeConcurrentEventMaster)
			{
				var profilePaymentInfo = DbContext.ProfilePaymentInfo.AsNoTracking().FirstOrDefault(x => x.FeeId == feeEvent.ID);
				if (profilePaymentInfo != null)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgUsingCanNotDelete),
						JsonRequestBehavior.AllowGet);
				}
			}

			var result = await DbContext.ConcurrentEventMaster.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				DbContext.ConcurrentEventMaster.Remove(result);
				await DbContext.SaveChangesAsync();
				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}


		public async Task<JsonCamelCaseResult> GetSecondData(string id, ConferenceConcurrentEventAndFeeModel model)
		{
			var sql = DbContext.FeeConcurrentEventMaster.AsNoTracking()
					.Where(x => x.ConcurrentEventId == id)
					.OrderBy(x => x.Sort)
					.ThenByDescending(x => x.CreateDate);

			int total = await sql.CountAsync();

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				price = x.Price.HasValue ? x.Price.Value.ToString("N2") : string.Empty,
				Currency = x.Currency,
				AttendenceIdentityId = x.AttendenceIdentityId == ConstValues.ApplicableForAll ? 
								Resources.ApplicableForAll : DbContext.AttendenceIdentityMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.AttendenceIdentityId)?.IdentityName,
				Number = x.Number,
                                Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				Creator = x.Creator,
				CreateIP = x.CreateIP,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
					x.CreateDate.Value.ToString("yyyy-MM-dd") :
					x.CreateDate.Value.ToString("MM/dd/yyyy")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("CreateSecondData/{ConferenceId}")]
		public async Task<JsonResult> CreateSecondData(ConferenceConcurrentEventAndFeeModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			foreach(var identityId in model.AttendenceIdentityId)
			{
				var result = await DbContext.FeeConcurrentEventMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConcurrentEventId == model.EventId &&
						 x.AttendenceIdentityId == identityId && x.Currency == model.Currency);

				//if (result != null)
				//{
				//	return JsonCamelCase(Utility.CreateFailJsonResult(
				//		string.Format(Resources.MsgRecordExist, Resources.ApplicableIdentity)),
				//		JsonRequestBehavior.AllowGet);
				//}

				if(result == null)
				{
					var FeeConcurrentEventMaster = new FeeConcurrentEventMaster
					{
						ID = Utility.GetTableId(ConstValues.TableName.FeeConcurrentEventMaster),
						ConcurrentEventId = model.EventId,
						Price = model.Price,
						Currency = model.Currency?.Trim(),
						AttendenceIdentityId = identityId,
						Number = model.Number,
						Status = model.ddlSecondStatus,
						Sort = model.txtSecondSort.HasValue ? model.txtSecondSort.Value : ConstValues.DefaultSort,
						Remark = model.txtSecondRemark?.Trim(),
						Creator = LoginUser.UserName,
						CreateIP = LoginUser.IP,
						CreateDate = DateTime.Now
					};

					DbContext.FeeConcurrentEventMaster.Add(FeeConcurrentEventMaster);
				}
			}

			
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
				JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("ModifySecondData/{ConferenceId}")]
		public async Task<JsonResult> ModifySecondData(ConferenceConcurrentEventAndFeeModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);
			
			var profilePaymentInfo = DbContext.ProfilePaymentInfo.AsNoTracking().FirstOrDefault(x => x.FeeId == model.SecondId);
			if (profilePaymentInfo != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgUsingCanNotChange),
					JsonRequestBehavior.AllowGet);
			}
			
			foreach (var identityId in model.AttendenceIdentityId)
			{
				var exist = await DbContext.FeeConcurrentEventMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConcurrentEventId == model.EventId &&
						x.AttendenceIdentityId == identityId &&
						x.Currency == model.Currency &&
						x.ID != model.SecondId);

				if (exist != null)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(
							string.Format(Resources.MsgRecordExist, Resources.ApplicableIdentity)),
							JsonRequestBehavior.AllowGet);
				}

				var result = await DbContext.FeeConcurrentEventMaster.FirstOrDefaultAsync(x => x.ID == model.SecondId);

				if (result != null)
				{
					result.ConcurrentEventId = model.EventId;
					result.Price = model.Price;
					result.Currency = model.Currency?.Trim();
					result.AttendenceIdentityId = identityId;
					result.Status = model.ddlSecondStatus;
					result.Number = model.Number;
					result.Sort = model.txtSecondSort.HasValue ? model.txtSecondSort.Value : ConstValues.DefaultSort;
					result.Remark = model.txtSecondRemark?.Trim();

					result.Updater = LoginUser.UserName;
					result.UpdateDate = DateTime.Now;
					result.UpdateIP = LoginUser.IP;

					await DbContext.SaveChangesAsync();

					
				}
				else
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
				}
			}
			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
							JsonRequestBehavior.AllowGet);

		}

		public async Task<JsonCamelCaseResult> GetSecondEditData(string id)
		{
			var data = await DbContext.FeeConcurrentEventMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (data != null)
			{
				var result = new
				{
					price = data.Price.HasValue ? data.Price.Value.ToString("N2") : string.Empty,
					currency = data.Currency,
					number = data.Number,
					attendenceIdentityId = data.AttendenceIdentityId,
					concurrentEventId = data.ConcurrentEventId,
					fee = data.Price.HasValue ? data.Price.Value : 0,
					sort = data.Sort,
					status = data.Status,
					remark = data.Remark
				};
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("DeleteSecondData/{ConferenceId}")]
		public async Task<JsonResult> DeleteSecondData(ConferenceConcurrentEventAndFeeModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var profilePaymentInfo = DbContext.ProfilePaymentInfo.AsNoTracking().FirstOrDefault(x => x.FeeId == model.SecondId);
			if (profilePaymentInfo != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgUsingCanNotDelete),
					JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.FeeConcurrentEventMaster.FirstOrDefaultAsync(x => x.ID == model.SecondId);

                        if (result != null)
			{
				DbContext.FeeConcurrentEventMaster.Remove(result);
				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}
	}
}